package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.wx.CloudService;
import com.cskaoyan.market.service.wx.WxAuthService;
import com.cskaoyan.market.service.wx.WxCouponService;
import com.cskaoyan.market.shiro.MarketToken;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/5/18 9:49
 * @Version 1.0
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {
    Map<String,Object> codeAndTime = new HashMap<>();
    @Autowired
    WxAuthService wxAuthService;
    @Autowired
    SecurityManager securityManager;
    @Autowired
    CloudService cloudService;
    @Autowired
    WxCouponService wxCouponService;
    //传递了一个json字符串请求参数，如何接收：？？？？？
    @PostMapping("login")
    public Object login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResponseUtil.badArgument();
        }
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketToken token = new MarketToken(username, password, "wx");
        try {
            subject.login(token);
        } catch (Exception e) {
            return ResponseUtil.fail(404, "用户名密码不匹配");
        }
        MarketUser user = (MarketUser) subject.getPrincipal();
        Session session = subject.getSession();
        //登录成功，往session域写入数据，但是随即你便会发现一个问题，那就是无论怎么获取，始终获取不到session域里面的数据
        session.setAttribute("user", user);
        Map<String, Object> data = new HashMap<>();
        data.put("token", session.getId());
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("nickName", user.getNickname());
        userInfo.put("avatarUrl", user.getAvatar());
        data.put("userInfo", userInfo);
        wxCouponService.updateStatus(wxAuthService.getByUsername(username).getId());
        return ResponseUtil.ok(data);
    }
    @PostMapping("regCaptcha")
    public Object regCaptcha(@RequestBody Map<String,String> map) {
        String mobile =  map.get("mobile");
        String code=null;
        try{
            code = cloudService.sms(mobile);
        }catch (Exception e){
            return ResponseUtil.fail(505,"验证码在一分钟内不能重复发送");
        }
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        codeAndTime.put("captchaCode", code);
        codeAndTime.put("captchaTime", System.currentTimeMillis());
        // 存储验证码和发送时间
/*        session.setAttribute("captchaCode", code);
        session.setAttribute("captchaSentTime", );*/
        return ResponseUtil.ok();
    }
    // 假设这是验证验证码的方法
    public boolean verifyCaptcha(String userInput) {
        // 从会话中获取验证码和发送时间
        String captchaCode = (String) codeAndTime.get("captchaCode");
        Long captchaSentTime = (Long) codeAndTime.get("captchaTime");
        if (captchaCode == null || captchaSentTime == null) {
            // 没有验证码或发送时间，可能是验证码已过期或被清除
            return false;
        }
        // 检查验证码有效期（例如30秒）
        long currentTime = System.currentTimeMillis();
        long expirationTime = captchaSentTime + 30 * 1000; // 30秒有效期
        if (currentTime > expirationTime) {
            // 验证码已过期
            return false;
        }
        // 检查用户输入的验证码是否正确
        return captchaCode.equals(userInput);
    }
    @PostMapping("register")
    public Object register(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String mobile = (String) map.get("mobile");
        String inputCode = (String) map.get("code");
        Map<String,Object> data=new HashMap<>();
        Map<String, String> userInfo = new HashMap<>();
        //验证码验证
        if (verifyCaptcha(inputCode)){
            MarketUser marketUser = wxAuthService.register(username, password, mobile);
            if (marketUser == null) {
                return ResponseUtil.fail(608, "该手机号已注册");
            }
            else {
                SecurityUtils.setSecurityManager(securityManager);
                Subject subject = SecurityUtils.getSubject();
                MarketToken token = new MarketToken(username, password, "wx");

                try {
                    subject.login(token); // 尝试登录
                    Session session = subject.getSession();
                    session.setAttribute("user", marketUser);
                    data.put("token", session.getId());
                    userInfo.put("nickName", marketUser.getNickname());
                    userInfo.put("avatarUrl", marketUser.getAvatar());
                    data.put("userInfo", userInfo);
                    return ResponseUtil.ok(data);
                } catch (AuthenticationException e) {
                    // 登录失败处理
                    return ResponseUtil.fail(605, "登录失败");
                }
            }
        }return ResponseUtil.fail(703, "验证码错误或已过期");
    }
    @PostMapping("reset")
    public Object reset(@RequestBody Map map) {
        String password = (String) map.get("password");
        String mobile = (String) map.get("mobile");
        String inputCode = (String) map.get("code");
        if (verifyCaptcha(inputCode)){
            wxAuthService.reset(password, mobile);
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail(703, "验证码错误");
    }
    @PostMapping("logout")
    public Object logout() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        if (session != null) {
            session.removeAttribute("user");
        }
        return ResponseUtil.ok();
    }
}
